package cn.ym.mall.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    private static DruidDataSource druidDataSource;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();// JUC 本地线程类，一个线程共享
    static {
        try {
            // 加载属性集配置文件
            InputStream is = DruidUtils.class.getClassLoader().getResourceAsStream("database.properties");
            // 属性集文件对象
            Properties properties = new Properties();
            properties.load(is);
            // 创建数据源对象
            druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DruidDataSource getDruidDataSource(){
        return druidDataSource;
    }

    /**
     * 获取连接
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = threadLocal.get();
            if (conn == null){
                conn = druidDataSource.getConnection();
                threadLocal.set(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 获取连接(事务控制)
     * @param isAuto
     * @return
     */
    public static Connection getConnection(boolean isAuto) {
        Connection conn = null;
        try {
            conn = threadLocal.get();
            if (conn == null){
                conn = druidDataSource.getConnection();
                conn.setAutoCommit(isAuto);
                threadLocal.set(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void close(){
        try {
            Connection conn = threadLocal.get();
            if (conn != null) {
                conn.close();
                threadLocal.set(null);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 事务提交
     */
    public static void commit(){
        try {
            Connection conn = threadLocal.get();
            if (conn != null) {
                conn.commit();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 事务回滚
     */
    public static void rollback(){
        try {
            Connection conn = threadLocal.get();
            if (conn != null) {
                conn.rollback();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
